//
//  rigestViewController.m
//  Drops
//
//  Created by dllo on 16/5/24.
//  Copyright © 2016年 Drops.er. All rights reserved.
//

#import "rigestViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <BmobSDK/Bmob.h>
#import "ZFK_buttonView.h"
#import "MBProgressHUD.h"
#define WWWW [UIScreen mainScreen].bounds.size.width
#define HHHH [UIScreen mainScreen].bounds.size.height
@interface rigestViewController () <UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic, strong)AVPlayer *player;
@property(nonatomic, strong)UITextField *IdText;
@property(nonatomic, strong)UITextField *passwordText;
@property(nonatomic, strong)UITextField *ensurePassword;
@property(nonatomic, strong)UIImageView *HeadImage;
@property(nonatomic, strong)MBProgressHUD *hud;
@end

@implementation rigestViewController

-(void)viewWillAppear:(BOOL)animated{
    
    [self.player play];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupForAVplayerView];
    UIVisualEffect *blurEffect;
    blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *visualEffectView;
    visualEffectView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1.5f];
    [visualEffectView setAlpha:0.4f];
    [UIView commitAnimations];
    [visualEffectView setFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:visualEffectView];
    
    self.HeadImage =[[UIImageView alloc]initWithFrame:CGRectMake(80, 80, 80, 80)];
    self.HeadImage.backgroundColor = [UIColor whiteColor];
    self.HeadImage.center = CGPointMake(WWWW / 2, 70);
    self.HeadImage.layer.cornerRadius = 40;
    self.HeadImage.layer.masksToBounds = YES;
    [self.view addSubview:self.HeadImage];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(80, 80, 80, 80);
    button.center = CGPointMake(WWWW / 2, 70);
    button.backgroundColor = [UIColor clearColor];
    button.layer.cornerRadius = 40;
    button.layer.masksToBounds = YES;
    [self.view addSubview:button];
    [button addTarget:self action:@selector(chiceImage:) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *firstLine = [[UIView alloc]initWithFrame:CGRectMake(WWWW / 8, 150 , WWWW * 3 / 4 , 1)];
    firstLine.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:firstLine];
    UILabel *IdLabel = [[UILabel alloc]initWithFrame:CGRectMake(WWWW / 8, 120, 50, 30)];
    IdLabel.text = @"账号:";
    IdLabel.font = [UIFont systemFontOfSize:18];
    IdLabel.textColor = [UIColor whiteColor];
    IdLabel.textAlignment = 1;
    IdLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:IdLabel];
    _IdText = [[UITextField alloc]initWithFrame:CGRectMake(WWWW / 8 + 50, 120, (WWWW * 3 / 4) - (WWWW / 8), 30)];
    _IdText.backgroundColor = [UIColor clearColor];
    _IdText.placeholder = @"请输入账号";
    _IdText.textAlignment = 1;
    _IdText.font = [UIFont systemFontOfSize:20];
    _IdText.delegate = self;
    [self.view addSubview:_IdText];
    
    UIView *secLine = [[UIView alloc]initWithFrame:CGRectMake(WWWW / 8, 200 , WWWW * 3 / 4 , 1)];
    secLine.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:secLine];
    UILabel *passwordLabel = [[UILabel alloc]initWithFrame:CGRectMake(WWWW / 8, 170, 50, 30)];
    passwordLabel.text = @"密码:";
    passwordLabel.font = [UIFont systemFontOfSize:18];
    passwordLabel.textColor = [UIColor whiteColor];
    passwordLabel.textAlignment = 1;
    passwordLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:passwordLabel];
    _passwordText = [[UITextField alloc]initWithFrame:CGRectMake(WWWW / 8 + 50, 170, (WWWW * 3 / 4) - (WWWW / 8), 30)];
    _passwordText.backgroundColor = [UIColor clearColor];
    _passwordText.placeholder = @"请输入密码";
    _passwordText.textAlignment = 1;
    _passwordText.secureTextEntry = YES;
    _passwordText.clearButtonMode = YES;
    _passwordText.font = [UIFont systemFontOfSize:20];
    _passwordText.delegate = self;
    [self.view addSubview:_passwordText];
    
    UIView *thirdLine = [[UIView alloc]initWithFrame:CGRectMake(WWWW / 8, 250 , WWWW * 3 / 4 , 1)];
    thirdLine.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:thirdLine];
    UILabel *ensurePasswordLabel = [[UILabel alloc]initWithFrame:CGRectMake(WWWW / 8, 220, 80, 30)];
    ensurePasswordLabel.text = @"确认密码:";
    ensurePasswordLabel.font = [UIFont systemFontOfSize:18];
    ensurePasswordLabel.textColor = [UIColor whiteColor];
    ensurePasswordLabel.textAlignment = 1;
    ensurePasswordLabel.backgroundColor = [UIColor clearColor];
    [self.view addSubview:ensurePasswordLabel];
    _ensurePassword = [[UITextField alloc]initWithFrame:CGRectMake(WWWW / 8 + 50, 220, (WWWW * 3 / 4) - (WWWW / 8), 30)];
    _ensurePassword.backgroundColor = [UIColor clearColor];
    _ensurePassword.placeholder = @"请再次输入密码";
    _ensurePassword.textAlignment = 1;
    _ensurePassword.secureTextEntry = YES;
    _ensurePassword.clearButtonMode = YES;
    _ensurePassword.font = [UIFont systemFontOfSize:20];
    _ensurePassword.delegate = self;
    [self.view addSubview:_ensurePassword];
    
    ZFK_buttonView *buttonView = [[ZFK_buttonView alloc] initWithFrame:CGRectMake(0, sHEIGHT / 2, sWIDTH, sHEIGHT / 2)];
    [self.view addSubview:buttonView];
    
    buttonView.loginBtn.frame = CGRectMake(0, 0, 0, 0);
    
    [buttonView.registBtn addTarget:self action:@selector(registAction:) forControlEvents:UIControlEventTouchUpInside];
    [buttonView.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)chiceImage:(UIButton *)button{
    UIActionSheet *acs = [[UIActionSheet alloc] initWithTitle:@"上传头像"
                                                     delegate:self
                                            cancelButtonTitle:@"取消"
                                       destructiveButtonTitle:nil
                                            otherButtonTitles:@"相册",@"拍照", nil];
    acs.tag = 1000;
    [acs showInView:self.view];
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUInteger sourceType = 0;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        switch (buttonIndex) {
            case 1:
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 2:
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            default:
                break;
        }
    }else{
        if (buttonIndex == 1) {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = sourceType;
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image withName:@"avatar.png"];
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"avatar.png"];
    UIImage *saveImage = [[UIImage alloc]initWithContentsOfFile:fullPath];
    [_HeadImage setImage:saveImage];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}
-(void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullPath atomically:NO];
}

- (void)setupForAVplayerView
{
    //创建播放图层
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame =[UIScreen mainScreen].bounds;
    [self.view.layer addSublayer:playerLayer];
}
- (AVPlayer *)player
{
    if (!_player) {
        AVPlayerItem *playerItem = [self getPlayItem];
        _player = [AVPlayer playerWithPlayerItem:playerItem];
        //设置重复播放
        _player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
        
        [[NSNotificationCenter defaultCenter]addObserver:self
                                                selector:@selector(__playerItemDidPlayToEndTimeNotification:)
                                                    name:AVPlayerItemDidPlayToEndTimeNotification
                                                  object:nil];
        
    }
    return _player;
}
- (void)__playerItemDidPlayToEndTimeNotification:(NSNotification *)sender
{
    [_player seekToTime:kCMTimeZero];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (AVPlayerItem *)getPlayItem
{
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"BridgeLoop-640p" ofType:@"mp4"];
    NSURL *url = [NSURL fileURLWithPath:filePath];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    return playerItem;
}

- (void)registAction:(UIButton *)button {
        if ( [self.IdText.text isEqualToString:@""]||[self.passwordText.text isEqualToString:@""]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"输入有问题,请重新输入" delegate:self cancelButtonTitle:@"重新输入" otherButtonTitles:nil, nil];
            [alert show];
        }else{
            if ([self.passwordText.text isEqualToString:self.ensurePassword.text]) {
                NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES) lastObject]stringByAppendingPathComponent:@"avatar.png"];
                BmobObject *users = [BmobObject objectWithClassName:@"users"];
                [users setObject:self.IdText.text forKey:@"userID"];
                [users setObject:self.passwordText.text forKey:@"userPassword"];
                [users setObject:self.HeadImage.image forKey:@"headhead"];
                BmobFile *bmobFile = [[BmobFile alloc]initWithFilePath:filePath];
                self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [users saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                    [bmobFile saveInBackground:^(BOOL isSuccessful, NSError *error) {
                        if (isSuccessful) {
                            [users setObject:bmobFile forKey:@"headhead"];
                            [users updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
                                if (isSuccessful) {
                                    [self.hud hide:YES afterDelay:0];
                                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"注册成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                    [alert show];
                                    [self dismissViewControllerAnimated:YES completion:^{
                                        
                                    }];
                                } else {
                                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片上传失败" delegate:self cancelButtonTitle:@"重新输入" otherButtonTitles:nil, nil];
                                    [alert show];
                                }
                                
                            }];
                        } else {
                            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"图片上传失败" delegate:self cancelButtonTitle:@"重新输入" otherButtonTitles:nil, nil];
                            [alert show];
                            
                        }
                        
                    }];
                    
                }];
            } else {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"两次密码不一致" delegate:self cancelButtonTitle:@"重新输入" otherButtonTitles:nil, nil];
                [alert show];
            }
        }
    
}
    

- (void)backAction:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:^{

    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    self.IdText.text = @"";
    self.passwordText.text = @"";
    self.ensurePassword.text = @"";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
